package org.example.util;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;

public class JsonBody extends HashMap<String, Object> {
    public enum Codes{
        SUCCESS     (0, "success"),
        ERROR       (500, "error"),
        AUTH_ERROR  (501, "auth error")
        ;
        private final int code;
        private final String info;

        Codes(int code, String info) {
            this.code = code;
            this.info = info;
        }
        public int code() {
            return code;
        }

        public String info() { return info; }
    }
    public static JsonBody custom(Codes code) {
        JsonBody ret = new JsonBody();
        ret.put("code", code.code());
        ret.put("msg", code.info());
        return ret;
    }
    public static JsonBody custom(Codes code, String msg) {
        JsonBody ret = new JsonBody();
        ret.put("code", code.code());
        ret.put("msg", msg);
        return ret;
    }

    public static JsonBody ok() {
        return custom(Codes.SUCCESS);
    }

    public static JsonBody ok(String msg) {
        return custom(Codes.SUCCESS, msg);
    }

    public static JsonBody error() {
        return custom(Codes.ERROR);
    }

    public static JsonBody error(String msg) {
        return custom(Codes.ERROR, msg);
    }

    public JsonBody set(String key, Object value) {
        super.put(key, value);
        return this;
    }

    public void setData(Object data) {
        this.put("data", data);
    }

    public String getJsonString() {
        try {
            return new ObjectMapper().writeValueAsString(this);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
